import axios from 'axios'
import URL from './urls'


function formatUrl(opts) {
    let {name,path,query}=opts;
    let url = URL[name];

    for (var p in path) {
        url = url.replace("\{\{" + p + "\}\}", params[p]);
    }
    for (var q in query) {
        if (url.indexOf('?') == -1) {
            url += "?";
        }
        url += "&" + q + "=" + query[q]
    }
    return url;
}


var instance = axios.create({
    baseURL:"/",
    timeout:1000
});

/**
 *
 * @param param [Object]
 *
 *  字段：name,path,query,body
 *
 */
export function fetch(param,type="get"){
    let url=formatUrl(param);
    let aysn=instance[type],
        data=type=="get"?param.query:param.body;
    return new Promise(function(yes,no){
        aysn(url,data)
            .then(function (response) {
                yes(response.data)
            })
            .catch(function (error) {
                console.log(error);
                no(error)
            })
    })

}

export default fetch;
